package com.jichangxiu.socket.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.jichangxiu.common.constant.Constants;
import com.jichangxiu.common.entity.bo.Record;
import com.jichangxiu.socket.filter.SocketFilter;
import org.atmosphere.config.service.*;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.Broadcaster;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@ManagedService(path = "/common/socket", atmosphereConfig = {"org.atmosphere.cpr.CometSupport.maxInactiveActivity=120000"}, broadcastFilters = {SocketFilter.class})
public class WebSocket {

    private static final long serialVersionUID = 1L;

    @Inject
    private AtmosphereResource r;

    /**
     * socket 转发对象
     */
    @Inject
    @Named("/common/socket")
    public static Broadcaster broadcaster;

    /**
     * 打开链接时触发
     *
     * @throws UnsupportedEncodingException 异常
     */
    @Ready
    public void onReady() throws UnsupportedEncodingException {
        System.out.println("用户 " + getUserInfoFromRequest(r.getRequest()) + " 上线");
    }

    @Disconnect
    public void onDisconnect(AtmosphereResourceEvent event) throws UnsupportedEncodingException {
        if (event.isCancelled()) {
            // 非正常关闭时触发，报错了
            System.out.println("用户 " + getUserInfoFromRequest(r.getRequest()) + " 意外断开连接");
        } else if (event.isClosedByClient()) {
            // 关闭连接时触发
            System.out.println("用户 " + getUserInfoFromRequest(r.getRequest()) + " 正常断开连接");
        }
    }

    /**
     * 接收到消息
     *
     * @param record 消息实体
     */
    @Message
    public void onMessage(Record record) {
        System.out.println("收到用户 " + getUserInfoFromRequest(r.getRequest()) + " 的消息内容 " + record.toJsonStr());
    }

    /**
     * 心跳
     *
     * @param event 活动
     */
    @Heartbeat
    public void onHeartbeat(AtmosphereResourceEvent event) {
        System.out.println("用户 " + getUserInfoFromRequest(r.getRequest()) + " 发来心跳 " + event.getResource().uuid());
    }

    private String getUserInfoFromRequest(HttpServletRequest request) {
        String userInfo = null;
        if (ObjectUtil.isNotEmpty(request)) {
            // 从请求头获取
            userInfo = request.getHeader(Constants.JCX_PROPERTIES.getServerProperties().getUserInfoToServerKey());
            if (StrUtil.isEmpty(userInfo))
                // 如果从请求头没有获取到有效 userId 那么则从请求参数中获取
                userInfo = request.getParameter(Constants.JCX_PROPERTIES.getServerProperties().getUserInfoToServerKey());
        }
        return userInfo;
    }

}
